<?php

class Core_Model_DbTable_Stores extends YouNet_Db_Table
{
	const TABLE_NAME		= 'stores';
	
	const STATUS_DELETED	= 0;
	const STATUS_SHOWN		= 1;
	const STATUS_HIDDEN		= 2;
	
	const LAYOUT_3x12		= 1;
	const LAYOUT_4x16		= 2;
	const LAYOUT_10xLIST	= 4;
	const LAYOUT_3xAll		= 8;
    
    const STATUS_NOT_ALLOW_COMMENT  = 0;
    const STATUS_ALLOW_COMMENT      = 1;
    
    const STATUS_SHOPPING_CART_SETTING = 1;

    protected $_name = self::TABLE_NAME;
	protected $_rowClass = 'Core_Model_Store';
	protected $_dependentTables = array('Core_Model_DbTable_Pages');
	static private $_instance;

	/**
	 *
	 * @return Core_Model_DbTable_Stores 
	 */
	public static function getInstance()
	{
		if (!(self::$_instance instanceof Core_Model_DbTable_Stores))
		{
			self::$_instance = new Core_Model_DbTable_Stores();
		}
		return self::$_instance;
	}

	public function createStoreFromParams($params)
	{
		//TODO: 
		return true;
	}

	public static function getLayoutOptions()
	{
		return array(
			self::LAYOUT_3x12		=> 'LAYOUT_3x12',
			self::LAYOUT_4x16		=> 'LAYOUT_4x16',
			self::LAYOUT_10xLIST	=> 'LAYOUT_10xLIST',
			self::LAYOUT_3xAll		=> 'LAYOUT_3xAll',
		);
	}
	
	public static function getLayoutName($key)
	{
		$options = self::getLayoutOptions();
		if (array_key_exists($key, $options))
		{
			return $options[$key];
		}
		else
		{
			return '';
		}
	}
	
	public static function getArrayLayouts($layouts)
	{
		$values = array();
		
		if(self::LAYOUT_3x12 & $layouts)
		{
			$values[] = self::LAYOUT_3x12;
		}
		
		if(self::LAYOUT_4x16 & $layouts)
		{
			$values[] = self::LAYOUT_4x16;
		}
		
		if(self::LAYOUT_10xLIST & $layouts)
		{
			$values[] = self::LAYOUT_10xLIST;
		}
		
		if(self::LAYOUT_3xAll & $layouts)
		{
			$values[] = self::LAYOUT_3xAll;
		}
		
		return $values;
	}
	
	/**
	 *
	 * @param int $id_store
	 * @param Core_Model_User $user
	 * @return Core_Model_Store
	 * @throws Exception 
	 */
	public static function getStoreByUser($id_store, Core_Model_User $user)
	{
		if ($id_store > 0)
		{
			$storeRow = self::getInstance()->findOne($id_store);
			if (!empty($storeRow) && ($storeRow->status != self::STATUS_DELETED) )
			{
				if ($user->hasPermissionWithStore($storeRow))
				{
					return $storeRow;
				}
			}
			throw new Exception('Access is denied');
		}
		return self::getInstance()->createRow();
	}

	public function findStoresByIdPage($id_page, $arrSort, $pageNumber)
	{
		$query = $this->_findStores(null, array($id_page), $arrSort);
		$paginator = Zend_Paginator::factory($query);
		$paginator->setCurrentPageNumber($pageNumber);
		$paginator->setItemCountPerPage(LIST_STORE_ITEM_PER_PAGE);
		return $paginator;
	}
	
	public function findStoresByUser($id_user, $arr_id_pages, $arrSort, $pageNumber)
	{
		$query = $this->_findStores($id_user, $arr_id_pages, $arrSort);
		$paginator = Zend_Paginator::factory($query);
		$paginator->setCurrentPageNumber($pageNumber);
		$paginator->setItemCountPerPage(LIST_STORE_ITEM_PER_PAGE);
		return $paginator;
	}

	private function _findStores($id_user, $arr_id_pages, $arrSort)
	{
		$select = $this->select()->setIntegrityCheck(false)
				->from(array('s' => self::TABLE_NAME), 's.*')
				->join
				(
					array('u' => Core_Model_DbTable_Users::TABLE_NAME), 'u.id = s.id_user', 
					array('name_user' => 'u.name')
				)
				->join
				(
					array(
						'p' => Core_Model_DbTable_Pages::TABLE_NAME), 
						's.id = p.id_store', 
						array(
							'id_page' => 'id_page',
							'page_name' => new Zend_Db_Expr("GROUP_CONCAT(DISTINCT p.name)"),
							'id_pages' => new Zend_Db_Expr("GROUP_CONCAT(DISTINCT p.id_page)"),	
						)
				)
				->joinLeft
				(
					array(
						'p1' => Core_Model_DbTable_Pages::TABLE_NAME), 
						's.id = p1.id_store', 
						array()
				);

		
		
		if (!empty($id_user))
		{
			$where =  $this->getDefaultAdapter()->quoteInto('s.id_user = ?', $id_user);
			$where .= $this->getDefaultAdapter()->quoteInto(' AND s.status <> ?', self::STATUS_DELETED);
			$select->where($where);
			
			if (!empty($arr_id_pages))
			{
				if (sizeof($arr_id_pages) > 1)
				{
					$where = $this->getDefaultAdapter()->quoteInto('s.status <> ?', self::STATUS_DELETED);
					$where .= $this->getDefaultAdapter()->quoteInto(' AND p1.id_page IN (?)', $arr_id_pages);
					$select->orWhere($where);
				}
				else if(sizeof($arr_id_pages) == 1)
				{
					$where = $this->getDefaultAdapter()->quoteInto('s.status <> ?', self::STATUS_DELETED);
					$where .= $this->getDefaultAdapter()->quoteInto(' AND p1.id_page = ?',  current($arr_id_pages));
					$select->orWhere($where);
				}
			}
		}
		else
		{
			if (sizeof($arr_id_pages) == 1)
			{
				$where = $this->getDefaultAdapter()->quoteInto('s.status <> ?', self::STATUS_DELETED);
				$where .= $this->getDefaultAdapter()->quoteInto(' AND p1.id_page = ?',  current($arr_id_pages));
				$select->where($where);
			}
		}

		$select->group('s.id');

		$isSort = false;
		
		if(!empty($arrSort['store_name']))
		{
			$arrSort['name'] = $arrSort['store_name'];
			unset($arrSort['store_name']);
		}
		
		if (!empty($arrSort))
		{
			foreach ($arrSort as $key => $value)
			{
				if (in_array($key, array('name', 'description', 'products', 'status')))
				{
					if (in_array($value, array('DESC', 'ASC')))
					{
						$isSort = true;
						$select->order("$key $value");
						$select->order('id DESC');
					}
				}
			}
		}
		if (!$isSort)
		{
			$select->order('id DESC');
		}
		return $select;
	}
	/**
	 *
	 * @param string $id_page
	 * @return Core_Model_Store
	 */
	public function findStoreByPage($id_page)
	{
		$key		= Core_Cache_IKeys::MODEL_STORE_BY_PAGE.'_'.$id_page;
		$data		= YouNet_Util::getObjectMemCache()->load($key);
		if( $data === false )
		{
			$select  = $this->select()->setIntegrityCheck(false)
					->from(array('s'=>self::TABLE_NAME),array('*'))
					->join(array('p'=>  Core_Model_DbTable_Pages::TABLE_NAME), 'p.id_store = s.id',array('page_name' => 'p.name'))
					->where('s.status = ?', self::STATUS_SHOWN)
					->where('p.id_page = ?', $id_page);
			$store = $this->fetchRow($select);
			if( $store )
			{
				YouNet_Util::getObjectMemCache()->save($store->toArray(),$key);
			}
			else
			{
				$store = $this->createRow();
			}
		}
		else
		{
            $dataRow = array(
                'table'     => $this,
                'readonly'  => true,
                'stored'    => true,
                'data'      => $data
            );
			$rowClass = $this->getRowClass();
            $store = new $rowClass($dataRow);
		}
		return $store;
	}

	public function getShareStore($id_store, $id_page)
	{
		$query = $this->select()
				->setIntegrityCheck(false)
				->from(array('s' => self::TABLE_NAME), array('s.*'))
				->join(array('pg' => Core_Model_DbTable_Pages::TABLE_NAME), 'pg.id_store = s.id', array('pg.name as page_name'))
				->where('pg.id_page = ?', $id_page)
				->where('s.id = ?',  $id_store);

		return $this->fetchRow($query);
	}
	public static function getListSupportedLanguage()
	{
		return array(
			'en_US' => 'English',
			'vi_VN' => 'Tiếng Việt'
		);
	}
}